import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  getChatSessions,
  getChatSessionDetail,
  createChatSession,
  deleteChatSession,
  updateChatSession
} from '@/apis/client/chat'

// 查询键
export const CHAT_QUERY_KEYS = {
  sessions: ['chat', 'sessions'],
  sessionDetail: (sessionId: string) => ['chat', 'session', sessionId],
} as const

// 获取聊天会话列表
export function useChatSessions() {
  return useQuery({
    queryKey: CHAT_QUERY_KEYS.sessions,
    queryFn: () => getChatSessions(),
    staleTime: 2 * 60 * 1000, // 2分钟内认为数据是新鲜的
    gcTime: 10 * 60 * 1000, // 10分钟后清除缓存
    retry: 1,
  })
}

// 获取聊天会话详情
export function useChatSessionDetail(sessionId: string) {
  return useQuery({
    queryKey: CHAT_QUERY_KEYS.sessionDetail(sessionId),
    queryFn: () => getChatSessionDetail(sessionId),
    enabled: !!sessionId,
    staleTime: 1 * 60 * 1000, // 1分钟内认为数据是新鲜的
    gcTime: 5 * 60 * 1000, // 5分钟后清除缓存
    retry: 1,
  })
}

// 创建新的聊天会话
export function useCreateChatSession() {
  const queryClient = useQueryClient()
  
  return useMutation({
    mutationFn: createChatSession,
    onSuccess: (newSession) => {
      // 更新会话列表缓存
      queryClient.invalidateQueries({ queryKey: CHAT_QUERY_KEYS.sessions })
      
      // 将新会话添加到缓存中
      queryClient.setQueryData(
        CHAT_QUERY_KEYS.sessionDetail(newSession.id),
        newSession
      )
    },
  })
}

// 删除聊天会话
export function useDeleteChatSession() {
  const queryClient = useQueryClient()
  
  return useMutation({
    mutationFn: deleteChatSession,
    onSuccess: (_, deletedSessionId) => {
      // 更新会话列表缓存
      queryClient.invalidateQueries({ queryKey: CHAT_QUERY_KEYS.sessions })
      
      // 移除被删除会话的详情缓存
      queryClient.removeQueries({ 
        queryKey: CHAT_QUERY_KEYS.sessionDetail(deletedSessionId) 
      })
    },
  })
}

// 更新聊天会话标题
export function useUpdateChatSessionTitle() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({ chatId, title }: { chatId: string; title: string }) =>
      updateChatSession(chatId, title),
    onSuccess: (updatedSession, { chatId }) => {
      // 更新会话列表缓存
      queryClient.invalidateQueries({ queryKey: CHAT_QUERY_KEYS.sessions })

      // 更新会话详情缓存
      queryClient.setQueryData(
        CHAT_QUERY_KEYS.sessionDetail(chatId),
        updatedSession
      )
    },
  })
}

// 刷新聊天会话列表
export function useRefreshChatSessions() {
  const queryClient = useQueryClient()
  
  return () => {
    queryClient.invalidateQueries({ queryKey: CHAT_QUERY_KEYS.sessions })
  }
}

// 刷新特定会话详情
export function useRefreshChatSessionDetail() {
  const queryClient = useQueryClient()
  
  return (sessionId: string) => {
    queryClient.invalidateQueries({ 
      queryKey: CHAT_QUERY_KEYS.sessionDetail(sessionId) 
    })
  }
}

// 预加载会话详情
export function usePrefetchChatSessionDetail() {
  const queryClient = useQueryClient()
  
  return (sessionId: string) => {
    queryClient.prefetchQuery({
      queryKey: CHAT_QUERY_KEYS.sessionDetail(sessionId),
      queryFn: () => getChatSessionDetail(sessionId),
      staleTime: 1 * 60 * 1000,
    })
  }
}

// 添加消息到会话缓存
export function useAddMessageToSession() {
  const queryClient = useQueryClient()
  
  return (sessionId: string, message: any) => {
    queryClient.setQueryData(
      CHAT_QUERY_KEYS.sessionDetail(sessionId),
      (oldData: any) => {
        if (!oldData) return oldData
        
        return {
          ...oldData,
          messages: [...(oldData.messages || []), message]
        }
      }
    )
  }
}
